package com.chen.collections;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;


public class Test {

	public static String[] getRandomPool(int min,int max,int n){  
	    int len = max-min+1;  
	      
	    if(max < min || n > len){  
	        return null;  
	    }  
	      
	    String[] source = new String[len];  
	       for (int i = min; i < min+len; i++){  
	        source[i-min] = String.valueOf(i);  
	       }  
	         
	       String[] result = new String[n];  
	       Random rd = new Random();  
	       int index = 0;  
	       for (int i = 0; i < result.length; i++) {  
	        //待选数组0到(len-2)随机一个下标  
	           index = Math.abs(rd.nextInt() % len--);  
	           //将随机到的数放入结果集  
	           result[i] = source[index];  
	           //将待选数组中被随机到的数，用待选数组(len-1)下标对应的数替换  
	           source[index] = source[len];  
	       }  
	       return result;  
	}  
	
	public static String[] getRandomPool2(int min,int max,int n){  
	    int len = max-min+1;  
	      
	    if(max < min || n > len){  
	        return null;  
	    }  
	      
	    String[] source = new String[len];  
	       for (int i = min; i < min+len; i++){  
	        source[i-min] = String.valueOf(i);  
	       }  
	         
	       String[] result = new String[n];  
	       List<String> list = Arrays.asList(source);
	       Collections.shuffle(list);
	       list = list.subList(0, n);
	       result = list.toArray(result);
	       return result;  
	}  

	public static void main(String[] args) {
		Random rd = new Random();  
		int n = rd.nextInt(10);
		System.out.println("n = " + n);
		long start = System.currentTimeMillis();
		String[] result = Test.getRandomPool(1, 1000, 900);
		for(String s : result){
			System.out.print(s + ",");
		}
		long end = System.currentTimeMillis();
		System.out.println("-------------" + " cost = " + (end-start) + "ms!");
		
		start = System.currentTimeMillis();
		String[] result2 = Test.getRandomPool2(1, 1000, 900);
		for(String s : result2){
			System.out.print(s + ",");
		}
		end = System.currentTimeMillis();
		System.out.println("-------------" + " cost = " + (end-start) + "ms!");
	}

}
